package com.cooper.scraper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import android.util.Log;

public class CustomFixExecutorService {
	
	public interface ThreadPoolStatusListener {

		public abstract void onBusy();

		public abstract void onIdle();
	}

	private static CustomFixExecutorService singleton = null;

	public static CustomFixExecutorService getInstance() {
		if (singleton == null) {
			singleton = new CustomFixExecutorService();
		}
		return singleton;
	}

	private ExecutorService threadPool;

	private ThreadPoolStatusListener statusListener;

	private boolean busy = false;

	private Map<String, Future<?>> requests = new HashMap<String, Future<?>>();

	private CustomFixExecutorService() {
		super();
		threadPool = Executors.newFixedThreadPool(Runtime.getRuntime()
				.availableProcessors() * Prefs.getThreadPoolSize());
	}

	public void run(String key, RunnerThread thread) {
		if (requests.get(key) != null) {
			Log.w("CustomFixExecutorService", "thread in request");
		} else
			requests.put(key, threadPool.submit(thread));
		cleanRequest();
	}

	public void cleanRequest() {
		List<String> removeKeys = new ArrayList<String>();

		for (Entry<String, Future<?>> request : requests.entrySet()) {
			if (request.getValue().isDone() || request.getValue().isCancelled()) {
				removeKeys.add(request.getKey());
			}
		}
		for (String key : removeKeys) {
			requests.remove(key);
		}
		if (!busy && requests.size() >= Prefs.getThreadMaxSize()) {
			busy = true;
			if (statusListener != null)
				statusListener.onBusy();
		}
	}

	public Set<String> keySet() {
		return requests.keySet();
	}

	public void setStatusListener(ThreadPoolStatusListener statusListener) {
		this.statusListener = statusListener;
	}
	
	public void cancel(String key){
		cancel(key,true);
	}

	public void cancel(String key, boolean cleanBefor) {
		if (cleanBefor)
			cleanRequest();
		Future<?> task = requests.get(key);
		if (task != null) {
			task.cancel(true);
			requests.remove(key);
			Log.d("CustomFixExecutorService",
					"cancel Download from cancel for key:" + key);
		}
	}

	public void cancel() {
		cleanRequest();
		Log.d("CustomFixExecutorService", "Downloader is cancel all");
		for (Entry<String, Future<?>> request : requests.entrySet()) {
			request.getValue().cancel(true);
		}
		requests.clear();
	}

}
